package com.chen.Sign.controller;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chen.Sign.common.Result;
import com.chen.Sign.mapper.JournalMapper;
import com.chen.Sign.pojo.Journal;
import com.chen.Sign.service.JournalService;
import com.chen.Sign.service.impl.JournalServiceImpl;
import com.chen.Sign.utils.JWTUtils;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;

import net.sf.jsqlparser.expression.DateTimeLiteralExpression.DateTime;

import java.time.Duration;
import java.util.*;

// 签到模块
@RestController
@Slf4j
@SuppressWarnings({"all"})
@CrossOrigin
@RequestMapping("/journal")
public class JournalController {

    @Autowired
    JournalServiceImpl journalService;

    @Autowired
    JournalMapper journalMapper;
    @Autowired
    RedisTemplate redisTemplate;

    // PC端签到结束
    @PostMapping("/recordend")
    public Result record(HttpServletRequest request) throws ParseException  {
        Result result = new Result();
        String token = request.getHeader("token");
        DecodedJWT tokenInfo = JWTUtils.getTokenInfo(token);
        Integer id = tokenInfo.getClaim("id").asInt();
        String username = tokenInfo.getClaim("username").asString();
        String content = request.getParameter("content");
        String createtimekey = request.getHeader("createtimekey");
        String create_time = (String) redisTemplate.opsForValue().get(createtimekey);
        String update_time = request.getParameter("update_time");
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date createtime = df.parse(create_time);
        Date updatetime = df.parse(update_time);
        Journal journal = new Journal();
        journal.setUsername(username);
        journal.setContent(content);
        journal.setCreate_time(create_time);
        journal.setUpdate_time(update_time);
        // 计算本周时间、总时间、本次时间
        // String start = df.format(DateTime.valueOf(create_time));
        Long begin = createtime.getTime();
        Long end = updatetime.getTime();
        // 得到毫秒级别的差值·----------------------------------------------------------
        long timeLag = end - begin;
        //天
        long day = timeLag / (24 * 60 * 60 * 1000);
        //小时
        long hour = (timeLag / (60 * 60 * 1000) - day * 24);
        //分钟
        long minute = ((timeLag / (60 * 1000)) - day * 24 * 60 - hour * 60);
        //秒，顺便说一下，1秒 = 1000毫秒
        long s = (timeLag / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - minute * 60);

        journal.setSum_time(String.valueOf(minute));


        Integer sumTimeday = 0;
        Integer sumTimeweek = 0;
        Integer sumTimeall = 0;
        String timedesc = null;
        Map<String, Object> mapDay = journalService.selectByNameDay(username);
        Map<String, Object> mapWeek = journalService.selectByNameWeek(username);
        Map<String, Object> mapAll = journalService.selectByNameAll(username);
        LinkedHashMap<String, Object> mapdesctime = journalService.selectDescTime(username);
        // 遍历一天内的时长
        Iterator<String> iteratorday = mapDay.keySet().iterator();
        while (iteratorday.hasNext()) {
            String key = iteratorday.next();
            String value = (String) mapDay.get(key);
            Integer summinuteday = Integer.valueOf(value);
            // 一天内的总时长
            sumTimeday += summinuteday;
        }
        // 遍历一周内的时长
        Iterator<String> iteratorweek = mapWeek.keySet().iterator();
        while (iteratorweek.hasNext()) {
            String key = iteratorweek.next();
            String value = (String) mapWeek.get(key);
            Integer summinuteweek = Integer.valueOf(value);
            // 一周内的总时长
            sumTimeweek += summinuteweek;
        }
        // 遍历所有时长
        Iterator<String> iteratorAll = mapAll.keySet().iterator();
        while (iteratorAll.hasNext()) {
            String key = iteratorAll.next();
            String value = (String) mapWeek.get(key);
            Integer summinuteall = Integer.valueOf(value);
            // 一周内的总时长
            sumTimeall += summinuteall;
        }
        // 小时
        Integer sumhourday = sumTimeday / 60;
        Integer sumhourweek = sumTimeweek / 60;
        Integer sumhourall = sumTimeall / 60;
        // 分钟
        Integer oddminuteday = sumTimeday % 60;
        Integer oddminuteweek = sumTimeweek % 60;
        Integer oddminuteall = sumTimeall % 60;
        // 封装一天时间
        String daytime = sumhourday + "小时" + oddminuteday + "分钟";
        // 封装一周的时间
        String weektime = sumhourweek + "小时" + oddminuteweek + "分钟";
        // 封装总时长
        String alltime = sumhourall + "小时" + oddminuteall + "分钟";

        // 返回一周时间排名
        int count = 0;
        Iterator<String> iteratortimedesc = mapAll.keySet().iterator();
        while (iteratortimedesc.hasNext()) {
            String key = iteratortimedesc.next();
            String value = (String) mapdesctime.get(key);
            ++count;
            if (value == username) {
                timedesc = "第" + count + "名";
            }
        }
        journal.setDaytime(daytime);
        journal.setWeektime(weektime);
        journal.setAlltime(alltime);
        journal.setWeektimedesc(timedesc);
        boolean flag = journalService.insertContent(journal);
        HashMap<String, String> map = new HashMap<>();
        if (flag) {
        /*    map.put("username", username);
            map.put("content", content);
            map.put("daytime", daytime);
            map.put("weektime", weektime);
            map.put("alltime", alltime);
            map.put("weektimedesc", timedesc);*/
            return result.insertContentok(map);
        } else {
            return result.insertContentno(map);
        }
    }

    // 小程序端签到结束
    @PostMapping("/recordendwx")
    public Result recordwx(HttpServletRequest request) throws ParseException  {
        Result result = new Result();
        String token = request.getHeader("token");
        DecodedJWT tokenInfo = JWTUtils.getTokenInfo(token);
        Integer id = tokenInfo.getClaim("id").asInt();
        String username = tokenInfo.getClaim("username").asString();
        String content = request.getParameter("content");
        String create_time = request.getParameter("create_time");
        String update_time = request.getParameter("update_time");
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date createtime = df.parse(create_time);
        Date updatetime = df.parse(update_time);
        Journal journal = new Journal();
        journal.setUsername(username);
        journal.setContent(content);
        journal.setCreate_time(create_time);
        journal.setUpdate_time(update_time);
        // 计算本周时间、总时间、本次时间
        // String start = df.format(DateTime.valueOf(create_time));
        Long begin = createtime.getTime();
        Long end = updatetime.getTime();
        // 得到毫秒级别的差值·----------------------------------------------------------
        long timeLag = end - begin;
        //天
        long day = timeLag / (24 * 60 * 60 * 1000);
        //小时
        long hour = (timeLag / (60 * 60 * 1000) - day * 24);
        //分钟
        long minute = ((timeLag / (60 * 1000)) - day * 24 * 60 - hour * 60);
        //秒，顺便说一下，1秒 = 1000毫秒
        long s = (timeLag / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - minute * 60);

        journal.setSum_time(String.valueOf(minute));


        Integer sumTimeday = 0;
        Integer sumTimeweek = 0;
        Integer sumTimeall = 0;
        String timedesc = null;
        Map<String, Object> mapDay = journalService.selectByNameDay(username);
        Map<String, Object> mapWeek = journalService.selectByNameWeek(username);
        Map<String, Object> mapAll = journalService.selectByNameAll(username);
        LinkedHashMap<String, Object> mapdesctime = journalService.selectDescTime(username);
        // 遍历一天内的时长
        Iterator<String> iteratorday = mapDay.keySet().iterator();
        while (iteratorday.hasNext()) {
            String key = iteratorday.next();
            String value = (String) mapDay.get(key);
            Integer summinuteday = Integer.valueOf(value);
            // 一天内的总时长
            sumTimeday += summinuteday;
        }
        // 遍历一周内的时长
        Iterator<String> iteratorweek = mapWeek.keySet().iterator();
        while (iteratorweek.hasNext()) {
            String key = iteratorweek.next();
            String value = (String) mapWeek.get(key);
            Integer summinuteweek = Integer.valueOf(value);
            // 一周内的总时长
            sumTimeweek += summinuteweek;
        }
        // 遍历所有时长
        Iterator<String> iteratorAll = mapAll.keySet().iterator();
        while (iteratorAll.hasNext()) {
            String key = iteratorAll.next();
            String value = (String) mapWeek.get(key);
            Integer summinuteall = Integer.valueOf(value);
            // 一周内的总时长
            sumTimeall += summinuteall;
        }
        // 小时
        Integer sumhourday = sumTimeday / 60;
        Integer sumhourweek = sumTimeweek / 60;
        Integer sumhourall = sumTimeall / 60;
        // 分钟
        Integer oddminuteday = sumTimeday % 60;
        Integer oddminuteweek = sumTimeweek % 60;
        Integer oddminuteall = sumTimeall % 60;
        // 封装一天时间
        String daytime = sumhourday + "小时" + oddminuteday + "分钟";
        // 封装一周的时间
        String weektime = sumhourweek + "小时" + oddminuteweek + "分钟";
        // 封装总时长
        String alltime = sumhourall + "小时" + oddminuteall + "分钟";

        // 返回一周时间排名
        int count = 0;
        Iterator<String> iteratortimedesc = mapAll.keySet().iterator();
        while (iteratortimedesc.hasNext()) {
            String key = iteratortimedesc.next();
            String value = (String) mapdesctime.get(key);
            ++count;
            if (value == username) {
                timedesc = "第" + count + "名";
            }
        }
        journal.setDaytime(daytime);
        journal.setWeektime(weektime);
        journal.setAlltime(alltime);
        journal.setWeektimedesc(timedesc);
        int insert = journalMapper.insert(journal);
        // boolean flag = journalService.insertContent(journal);
        HashMap<String, String> map = new HashMap<>();
        if (insert > 0) {
        /*    map.put("username", username);
            map.put("content", content);
            map.put("daytime", daytime);
            map.put("weektime", weektime);
            map.put("alltime", alltime);
            map.put("weektimedesc", timedesc);*/
            return result.insertContentok(map);
        } else {
            return result.insertContentno(map);
        }
    }

    // 签到开始
    @PostMapping("/recordstart")
    public Result recordstart(HttpServletRequest request) {
        String token = request.getHeader("token");
        DecodedJWT tokenInfo = JWTUtils.getTokenInfo(token);
        Integer id = tokenInfo.getClaim("id").asInt();
        String username = tokenInfo.getClaim("username").asString();
        String create_time = request.getParameter("create_time");
        if (create_time!=null) {
            String createtimekey = create_time + UUID.randomUUID() +"";
            redisTemplate.opsForValue().set(createtimekey,create_time, Duration.ofHours(24L));
            return new Result(1,"开始签到成功","");
        }
        return new Result(0,"开始签到失败","");

    }

    // 遍历所有数据接口
    @GetMapping("/takeout")
    public Result takeOut(int page,int pageSize,HttpServletRequest request) {
        String token = request.getHeader("token");
        DecodedJWT tokenInfo = JWTUtils.getTokenInfo(token);
        Integer id = tokenInfo.getClaim("id").asInt();
        String username = tokenInfo.getClaim("username").asString();
        Page<Journal> pageInfo = new Page<>(page,pageSize);
        LambdaQueryWrapper<Journal> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(Journal::getUsername,username);
        journalService.page(pageInfo,queryWrapper);
        return new Result(1,"查找成功",pageInfo);
    }

    // 累计签到天数

    // 连续签到天数
}
